package cn.doitedu.basic.jdk.jvmhook;

import java.util.Random;

/**
 * Created by yuanhailong on 2021/10/1.
 *
 * 测试JVM 退出的钩子，JVM退出(正常退出，活调用System.exit)的时候可做一些资源清理等工作
 *
 * 参考 Flink 源码
 * ShutdownHookUtil.addShutdownHook
 *
 */
public class JVMShutdownHookDemo {


    public static void main(String[] args) throws Exception{
        System.out.println("JVMShutdownHookDemo test start");
        Runtime.getRuntime().addShutdownHook(new MyShutdownHookThread("JVM 退出钩子"));
        System.out.println("JVMShutdownHookDemo test end");
        Thread.sleep(new Random().nextInt(10)*1000);
    }


    static class MyShutdownHookThread extends Thread{

        private String msg;

        MyShutdownHookThread(String msg){
            this.msg=msg;
        }

        @Override
        public void run() {
            System.out.println(msg);

            System.out.println("MyShutdownHookThread:系统退出资源清理");

            //如关闭连接
            //释放资源等动作
        }
    }

}



